package cn.sxw.ld.common.utils;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.io.File;

/**
 * ClassName:ValidateCodeUtils
 * Package:cn.sjxy.graduation.common.utils
 * Description: 随机生成验证码工具类
 *
 * @Date:2023/2/27 21:10
 * @Author:SXW
 */
@Component
@Slf4j
public class EmailUtils {
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 自己邮箱地址
     */
    @Value("${spring.mail.username}")
    private String myEmail;

    @Value("${spring.mail.username}")
    private String recipientEmail;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 随机生成验证码
     */
    public static String getRandomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 发送验证码注册
     *
     * @param addressee
     * @param subject
     * @param code
     * @return
     */
    public Boolean sendEmail(String addressee, String subject, String code) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject(subject);//主题
            //内容
            mailMessage.setText(code);
            // 收件人地址
            mailMessage.setTo(addressee);
            // 发件人地址
            mailMessage.setFrom(myEmail);
            // 发送
            mailSender.send(mailMessage);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
